
package com.gitee.qdbp.jdbc.biz;

import java.util.List;
import com.gitee.qdbp.able.jdbc.condition.TableJoin;
import com.gitee.qdbp.able.jdbc.condition.TableJoin.JoinItem;
import com.gitee.qdbp.jdbc.api.JoinQueryer;
import com.gitee.qdbp.jdbc.api.SqlBoot;
import com.gitee.qdbp.jdbc.api.SqlBufferJdbcOperations;
import com.gitee.qdbp.jdbc.model.AllFieldColumn;
import com.gitee.qdbp.jdbc.plugins.DbPluginHelper;
import com.gitee.qdbp.jdbc.plugins.EntityDataStateFillStrategy;
import com.gitee.qdbp.jdbc.plugins.EntityFieldFillExecutor;
import com.gitee.qdbp.jdbc.plugins.EntityFieldFillStrategy;
import com.gitee.qdbp.jdbc.sql.build.QuerySqlHelper;

/**
 * 基础表连接查询操作
 *
 * @author 赵卉华
 * @version 190606
 */
public class JoinQueryerImpl<T> extends BaseQueryerImpl<T> implements JoinQueryer<T> {

    private final String majorTableAlias;

    public JoinQueryerImpl(TableJoin t, Class<T> r, SqlBoot sqlBoot, SqlBufferJdbcOperations jdbc) {
        super(new QuerySqlHelper(t, sqlBoot), newEntityFieldFillExecutor(t, sqlBoot), jdbc,
            sqlBoot.plugins().getRowToBeanMapper(t, r));
        this.majorTableAlias = t.getMajor().getTableAlias();
        List<JoinItem> joins = t.getJoins();
        for (JoinItem item : joins) {
            entityFieldFillExecutor.fillQueryWhereDataState(item.getWhere(), item.getTableAlias());
        }
    }

    private static EntityFieldFillExecutor newEntityFieldFillExecutor(TableJoin tables, SqlBoot sqlBoot) {
        DbPluginHelper plugins = sqlBoot.plugins();
        AllFieldColumn<?> allFields = plugins.parseAllFieldColumns(tables);
        if (allFields.isEmpty()) {
            throw new IllegalArgumentException("fields is empty");
        }
        EntityFieldFillStrategy fieldFillStrategy = plugins.getEntityFieldFillStrategy();
        EntityDataStateFillStrategy<?> dataStateFillStrategy = plugins.getEntityDataStateFillStrategy();
        return new EntityFieldFillExecutor(allFields, fieldFillStrategy, dataStateFillStrategy);
    }

    /** {@inheritDoc} **/
    @Override
    protected String getMajorTableAlias() {
        return majorTableAlias;
    }

    @Override
    public QuerySqlHelper sqlHelper() {
        return sqlHelper;
    }

}
